package com.zjk.product.service;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author: gfk
 * @create: 2022/11/3
 * @Description:
 * @FileName: ListenerMessage
 * @History:
 * @自定义内容：
 */
@RabbitListener(queues = {"Queue_audit"})
@Component
public class ListenerMessage {

    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 保证消息的可靠性
     * @param channel
     * @param message
     * @param msg
     * @throws IOException
     */
    @RabbitHandler
    private void  ravMessage(Channel channel, Message message, String msg) throws IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        String messageId = message.getMessageProperties().getMessageId();

        String messageList = (String) redisTemplate.opsForHash().get("revMessageList", messageId);
        if (messageList!=null){//已经处理了该消息
                channel.basicAck(deliveryTag,false);
                return;
        }

        System.out.println("接收到的消息"+msg);
        redisTemplate.opsForHash().put("revMessageList",messageId,"ok");
        channel.basicAck(deliveryTag,false);
    }
}
